# 导入相应的模块
import pygame
from pygame.locals import *
import time, random


class Boom:
    '''绘制游戏结束场面'''
    def __init__(self, screen_temp):
        self.x = -50
        self.y = -20
        self.screen = screen_temp
        self.image = pygame.image.load("./images/timg.jpg")


    def display(self):
        '''绘制爆炸图案'''
        self.screen.blit(self.image, (self.x, self.y))

class Bullet:
    '''子弹类'''

    def __init__(self, screen_temp, x, y):
        self.x = x + 53
        self.y = y
        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image, (self.x, self.y))

    def move(self):
        self.y -= 10
        if self.y <= -20:
            return True

class EBullet:
    '''子弹类'''

    def __init__(self, screen_temp, x, y):
        self.x = x + 53
        self.y = y+130
        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image, (self.x, self.y))

    def move(self):
        self.y += 10
        if self.y >=568:
            return True



class HeroPlane:
    '''玩家飞机（英雄）'''
    life=3
    def __init__(self, screen_temp):
        self.x = 200
        self.y = 400
        self.screen = screen_temp
        self.image = pygame.image.load("./images/me.png")
        self.bullet_list = []  # 用于存放玩家的子弹列表
        # self.life=3 ##玩家飞机复活次数

    def display(self):
        '''绘制玩家飞机'''
        # 绘制子弹
        for b in self.bullet_list:
            b.display()
            if b.move():
                self.bullet_list.remove(b)
        self.screen.blit(self.image, (self.x, self.y))

    def move_left(self):
        '''左移动飞机'''
        self.x -= 5
        if self.x <= 0:
            self.x = 0

    def move_right(self):
        '''右移动飞机'''
        self.x += 5
        if self.x >= 406:
            self.x = 406

    def fire(self):
        self.bullet_list.append(Bullet(self.screen, self.x, self.y))
        print(len(self.bullet_list))

class EnemyPlane:
    '''敌机类'''

    def __init__(self, screen_temp):
        self.x = random.choice(range(408))
        self.y = -75
        self.screen = screen_temp
        self.image = pygame.image.load("./images/e" + str(random.choice(range(3))) + ".png")
        self.bullet_list = []  # 用于存放敌机的子弹列表



    def display(self):
        '''绘制敌机'''
        for b in self.bullet_list:
            b.display()
            if b.move():
                self.bullet_list.remove(b)
        self.screen.blit(self.image, (self.x,self.y))

    def move(self, hero):
        self.y += 4
        # 敌机出屏幕
        if self.y > 568:
            return True

        # 遍历所有玩家子弹,并执行碰撞检测
        for bo in hero.bullet_list:
            if bo.x > self.x + 12 and bo.x < self.x + 92 and bo.y > self.y + 20 and bo.y < self.y + 60:
                hero.bullet_list.remove(bo)
                return True





    def hit(self,hero):##飞机检测碰撞
        if (hero.x-116<self.x<hero.x+106 and self.y <=hero.y+76 and self.y>hero.y-74) :
            print("敌机位置",self.x,self.y)
            print("我机位置",hero.x,hero.y)
            print(self.image)
            print("碰撞")
            return True

    def fire(self,hero):
        self.bullet_list.append(EBullet(self.screen, self.x, self.y))

    def check_shot(self,hero):
        for bi in self.bullet_list:
            print("内函数子弹和我机位置")
            print(bi.x, bi.y, hero.x, hero.y)
            if bi.x >= hero.x and bi.x < hero.x + 92 and bi.y >= hero.y and bi.y <= hero.y+76:
                print("内函数中弹")
                print(bi.x,bi.y,hero.x,hero.y)
                self.bullet_list.remove(bi)
                print("子弹个数",len(self.bullet_list))
                return True





def key_control(hero_temp):
    '''键盘控制函数'''
    # 执行退出操作
    for event in pygame.event.get():
        if event.type == QUIT:
            print("exit()")
            exit()

    # 获取按键信息
    pressed_keys = pygame.key.get_pressed()
    # print(pressed_keys)
    # 做判断，并执行对象的操作
    if pressed_keys[K_LEFT] or pressed_keys[K_a]:
        print("Left...")
        hero_temp.move_left()

    elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
        print("Right...")
        
        hero_temp.move_right()

    if pressed_keys[K_SPACE]:
        print("space...")
        backgroundmusic = pygame.mixer_music.load("./music/fire.mp3")  ##设置发射子弹声音
        pygame.mixer.music.play() #发射声音
        pygame.mixer.music.stop  #停止声音，并继续背景音乐
        backgroundmusic = pygame.mixer_music.load("./music/bgm.mp3")
        pygame.mixer.music.play()
        hero_temp.fire()


def main():
    '''主程序函数 '''
    # 创建游戏窗口，
    pygame.init()
    screen = pygame.display.set_mode((512, 568), 0, 0)
    pygame.display.set_caption("飞机大战") ###设置标题

    # 创建一个游戏背景
    background = pygame.image.load("./images/bg2.jpg")
    backgroundmusic =pygame.mixer_music.load("./music/bgm.mp3")
    pygame.mixer.music.play()
    # 创建玩家飞机（英雄）
    hero = HeroPlane(screen)

    m = -968
    enemylist = []  # 存放敌机的列表
    while hero.life:
        if not pygame.mixer.music.get_busy:
            backgroundmusic = pygame.mixer_music.load("./music/bgm.mp3")
            pygame.mixer.music.play()
        # 绘制玩家飞机并显示
        hero.image=pygame.image.load("./images/me.png")

        hero.display()
        # 绘制画面
        screen.blit(background, (0, m))
        m += 2
        if m >= -200:
            m = -968

        # 绘制玩家飞机
        hero.display()

        # 执行键盘控制
        key_control(hero)

        # 随机绘制敌机
        if random.choice(range(50)) == 10:
            enemylist.append(EnemyPlane(screen))
        # 遍历敌机并绘制移动
        for em in enemylist:
            print("敌机个数",len(enemylist))
            print(enemylist.index(em),"号敌机位置",em.x,em.y,"相差距离x",abs(em.x-hero.x)," y",abs(em.y-hero.y))
            print( "我机位置", hero.x, hero.y)
            em.display()

            if (em.y-(-75))%45 ==0 and em.y+116 <hero.y:###按定时发射子弹
                em.fire(hero)

            print("敌机展示")
            if em.move(hero):
                print("敌机消除")
                em.image = pygame.image.load("./images/boom2.png").convert()
                em.display()
                pygame.display.update()
                pygame.time.delay(100)
                enemylist.remove(em)
            if em.hit(hero):##撞机
                print("撞机")
                enemylist.clear()
                em.image= pygame.image.load("./images/boom2.png").convert()
                print("敌机消除")
                print("我机生命减一")
                hero.life-=1
                print("我机生命",hero.life)
                print("爆炸")
                hero.image = pygame.image.load("./images/boom2.png").convert()
                hero.display()
                em.display()
                backgroundmusic = pygame.mixer_music.load("./music/boom.mp3")  ##中枪声音，生命值少一
                pygame.mixer.music.play()
                print("爆炸场面")
                pygame.display.update()
                print("暂停3秒")
                pygame.time.delay(3000)
                print("暂停3秒结束")
            if em.check_shot(hero):
                enemylist.clear()
                em.bullet_list.clear()
                print("我机生命减一")
                hero.life -= 1
                print("我机生命", hero.life)
                print("爆炸")
                backgroundmusic = pygame.mixer_music.load("./music/boom.mp3")
                pygame.mixer.music.play()
                hero.image = pygame.image.load("./images/boom2.png").convert()
                hero.display()
                em.display()
                print("爆炸场面")
                pygame.display.update()
                print("暂停3秒")
                pygame.time.delay(3000)
                print("暂停3秒结束")
                # pygame.time.wait(3000)
        # 更新显示
        pygame.display.update()

        # 定时显示
        time.sleep(0.04)
    else:
        print("死亡三次，游戏结束")
        backgroundmusic = pygame.mixer_music.load("./music/gameover.mp3") #GAME OVER声音
        pygame.mixer.music.play()
        screen.blit(background, (0, m))
        boom=Boom(screen)
        boom.display()
        pygame.display.update()
        pygame.time.delay(3000)

# 判断当前是否是主运行程序，并调用
if __name__ == "__main__":
    main()
